package com.yunxiangyue

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.makeramen.roundedimageview.RoundedImageView
import com.yunxiangyue.app.R

class publish : AppCompatActivity(), View.OnClickListener {
    var count=-1
    lateinit var mlauncher:ActivityResultLauncher<Intent>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_publish)
        val actionBar=supportActionBar
        actionBar?.hide()
        findViewById<Button>(R.id.backk).setOnClickListener(this)
        findViewById<ImageView>(R.id.selectPic).setOnClickListener(this)

        mlauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback {
                if(it.resultCode== RESULT_OK){
                    val intent=it.data
                    val UriPic=intent?.data
                    if(UriPic!=null){
                        if(count%4==0){
                            findViewById<RoundedImageView>(R.id.img1).setImageURI(UriPic)
                        }else if(count%4==1){
                            findViewById<RoundedImageView>(R.id.img2).setImageURI(UriPic)
                        }else if(count%4==3){
                            findViewById<RoundedImageView>(R.id.img3).setImageURI(UriPic)
                        }else{
                            findViewById<RoundedImageView>(R.id.img4).setImageURI(UriPic)
                        }
                    }
                }
            })
    }

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.backk -> {
                finish()
            }
            R.id.selectPic -> {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1);
                } else {
                    //访问相册
                    val intent=Intent(Intent.ACTION_GET_CONTENT)
                    intent.setType("image/*")
                    mlauncher.launch(intent)
                }
                count++
            }
        }
    }

}